import collections
class Solution(object):
    def minimumWeight(self, n, edges, src1, src2, dest):
        d = collections.defaultdict(dict)
        d_reverse = collections.defaultdict(dict)
        for u, v, t in edges:
            if v not in d[u]:
                d[u][v] = t
                d_reverse[v][u] = t
            else:
                d[u][v] = min(d[u][v], t)
                d_reverse[v][u] = min(d_reverse[v][u], t)
        s_1 = [-1] * n
        s_1[src1] = 0
        s_2 = [-1] * n
        s_2[dest] = 0
        def dfs_1(u, val):
            for v, t in d[u].items():
                if s_1[v] == -1 or t + val < s_1[v]:
                    s_1[v] = t + val
                    if v != dest:
                        dfs_1(v, s_1[v])
        dfs_1(src1, 0)
        def dfs_2(u, val):
            for v, t in d_reverse[u].items():
                if s_2[v] == -1 or t + val < s_2[v]:
                    s_2[v] = t + val
                    if v!= src1:
                        dfs_2(v, s_2[v])
        dfs_2(dest, 0)
        self.min_val = float('inf')
        s_3 = [-1] * n
        s_3[src2] = 0
        def dfs_3(u, val):
            if s_1[u] >= 0 and s_2[u] >= 0:
                self.min_val = min(self.min_val, s_1[u] + s_2[u] + val)
            if u != dest:
                for v, t in d[u].items():
                    if s_3[v] == -1 or t + val < s_3[v]:
                        s_3[v] = t + val
                        dfs_3(v, s_3[v])
        dfs_3(src2, 0)
        if self.min_val < float('inf'):
            return self.min_val
        else:
            return -1
                

            

data = Solution()
n = 6
edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]]
src1 = 0
src2 = 1
dest = 5
print(data.minimumWeight(n, edges, src1, src2, dest))